from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                             QLineEdit, QPushButton, QMessageBox)
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QFont
import logging
import os
import sys

# 添加父目录到系统路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(os.path.dirname(current_dir))
sys.path.append(parent_dir)

from biz.login_manager2 import LoginManager

logger = logging.getLogger(__name__)

class LoginDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        logger.debug("初始化登录对话框")
        self.login_manager = LoginManager()
        self.sms_result = None  # 存储短信发送结果
        self.need_sms_up = False  # 是否需要上行短信
        self.sms_up_content = ""  # 上行短信内容
        self.sms_up_number = ""  # 上行短信号码
        self.countdown = 0
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_send_button)
        
        # 设置窗口属性
        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        self.setWindowFlags(Qt.WindowType.Window | Qt.WindowType.WindowCloseButtonHint)
        logger.debug("设置窗口模态和标志")
        
        self.init_ui()
        logger.debug("登录对话框初始化完成")
        
    def init_ui(self):
        """初始化UI"""
        logger.debug("开始初始化登录对话框UI")
        self.setWindowTitle("登录uu账号")
        self.setFixedSize(400, 300)
        
        layout = QVBoxLayout()
        layout.setSpacing(10)
        layout.setContentsMargins(20, 20, 20, 20)
        self.setLayout(layout)  # 确保设置了布局
        
        # 标题
        title_label = QLabel("登录uu账号")
        title_font = QFont()
        title_font.setPointSize(16)
        title_label.setFont(title_font)
        layout.addWidget(title_label)
        
        # 手机号输入
        phone_layout = QHBoxLayout()
        phone_label = QLabel("手机号")
        phone_label.setStyleSheet("color: black;")
        phone_label.setFixedWidth(60)
        self.phone_edit = QLineEdit()
        self.phone_edit.setPlaceholderText("请输入手机号")
        self.send_code_btn = QPushButton("发送验证码")
        self.send_code_btn.setStyleSheet("""
            QPushButton {
                background-color: #409EFF;
                color: white;
                border: none;
                padding: 5px 10px;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #66B1FF;
            }
            QPushButton:disabled {
                background-color: #A0CFFF;
            }
        """)
        self.send_code_btn.clicked.connect(self.send_verification_code)
        phone_layout.addWidget(phone_label)
        phone_layout.addWidget(self.phone_edit)
        phone_layout.addWidget(self.send_code_btn)
        layout.addLayout(phone_layout)
        
        # 提示信息
        tip_label = QLabel("若无法发送验证码，请到您的APP或网站发送一次验证码，然后再回来重试！")
        tip_label.setStyleSheet("color: gray; font-size: 12px;")
        tip_label.setWordWrap(True)
        layout.addWidget(tip_label)
        
        # 验证码输入
        code_layout = QHBoxLayout()
        code_label = QLabel("验证码")
        code_label.setStyleSheet("color: black;")
        code_label.setFixedWidth(60)
        self.code_edit = QLineEdit()
        self.code_edit.setPlaceholderText("请输入验证码")
        code_layout.addWidget(code_label)
        code_layout.addWidget(self.code_edit)
        layout.addLayout(code_layout)
        
        # 按钮
        btn_layout = QHBoxLayout()
        self.confirm_btn = QPushButton("确定")
        self.confirm_btn.setStyleSheet("""
            QPushButton {
                background-color: #409EFF;
                color: white;
                border: none;
                padding: 8px 20px;
                border-radius: 4px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #66B1FF;
            }
        """)
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.setStyleSheet("""
            QPushButton {
                background-color: #F5F7FA;
                color: #606266;
                border: 1px solid #DCDFE6;
                padding: 8px 20px;
                border-radius: 4px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #FFFFFF;
                color: #409EFF;
                border-color: #409EFF;
            }
        """)
        
        self.confirm_btn.clicked.connect(self.do_login)
        self.cancel_btn.clicked.connect(self.reject)
        
        btn_layout.addStretch()
        btn_layout.addWidget(self.confirm_btn)
        btn_layout.addWidget(self.cancel_btn)
        layout.addStretch()
        layout.addLayout(btn_layout)
        
        logger.debug("登录对话框UI初始化完成")
        
    def send_verification_code(self):
        """发送验证码"""
        logger.debug("开始发送验证码")
        phone = self.phone_edit.text().strip()
        if not phone:
            QMessageBox.warning(self, "提示", "请输入手机号")
            return
            
        if not phone.isdigit() or len(phone) != 11:
            QMessageBox.warning(self, "提示", "请输入正确的手机号")
            return
            
        # 发送验证码
        try:
            self.sms_result = self.login_manager.send_sms_code(mobile=phone)
            
            if isinstance(self.sms_result, tuple):
                # 需要上行短信
                self.need_sms_up = True
                self.sms_up_content, self.sms_up_number = self.sms_result
                
                # 显示上行短信信息
                message = f"请发送短信内容 '{self.sms_up_content}' 到号码 {self.sms_up_number}，然后点击确定按钮登录"
                QMessageBox.information(self, "需要上行短信", message)
                
                # 修改验证码输入框提示
                self.code_edit.setPlaceholderText("已发送上行短信后请点击确定")
                self.code_edit.setEnabled(False)
                
                # 开始倒计时
                self.countdown = 60
                self.send_code_btn.setEnabled(False)
                self.timer.start(1000)  # 每秒更新一次
                logger.debug("需要上行短信，已提示用户")
            elif self.sms_result:
                # 短信验证码发送成功
                self.need_sms_up = False
                
                # 开始倒计时
                self.countdown = 60
                self.send_code_btn.setEnabled(False)
                self.timer.start(1000)  # 每秒更新一次
                QMessageBox.information(self, "提示", self.sms_result)
                logger.debug("验证码发送成功")
            else:
                # 发送失败
                QMessageBox.warning(self, "提示", "发送验证码失败，请稍后重试")
                logger.error("验证码发送失败，返回为空")
        except Exception as e:
            QMessageBox.warning(self, "提示", f"发送验证码出错: {str(e)}")
            logger.error(f"发送验证码异常: {str(e)}")
            
    def update_send_button(self):
        """更新发送按钮状态"""
        logger.debug("更新发送按钮状态")
        self.countdown -= 1
        if self.countdown <= 0:
            self.timer.stop()
            self.send_code_btn.setEnabled(True)
            self.send_code_btn.setText("发送验证码")
        else:
            self.send_code_btn.setText(f"重新发送({self.countdown})")
            
    def do_login(self):
        """执行登录"""
        logger.debug("开始执行登录")
        phone = self.phone_edit.text().strip()
        
        if not phone:
            QMessageBox.warning(self, "提示", "请输入手机号")
            return
            
        if not self.sms_result:
            QMessageBox.warning(self, "提示", "请先获取验证码")
            return
            
        try:
            user_info = {}
            
            if self.need_sms_up:
                # 使用短信上行登录
                logger.debug("使用短信上行登录")
                user_info = self.login_manager.login_with_sms_up(mobile=phone)
            else:
                # 使用短信验证码登录
                code = self.code_edit.text().strip()
                if not code:
                    QMessageBox.warning(self, "提示", "请输入验证码")
                    return
                    
                logger.debug("使用短信验证码登录")
                user_info = self.login_manager.login_with_sms_code(mobile=phone, code=code)
            
            if user_info:
                # 登录成功
                # 从token中提取用户ID（如果可能的话）
                user_id = user_info.get('user_id', 0)
                
                # 如果user_id不存在，尝试从token中提取
                if not user_id and 'token' in user_info:
                    try:
                        # JWT token通常由三部分组成，用.分隔，第二部分是payload
                        token_parts = user_info['token'].split('.')
                        if len(token_parts) >= 2:
                            import base64
                            import json
                            # 解码payload部分，处理填充问题
                            payload_part = token_parts[1]
                            # 添加填充使其长度为4的倍数
                            padding_needed = len(payload_part) % 4
                            if padding_needed:
                                payload_part += '=' * (4 - padding_needed)
                            # 使用更安全的解码方式
                            decoded = base64.urlsafe_b64decode(payload_part)
                            payload = json.loads(decoded.decode('utf-8', errors='ignore'))
                            if 'Id' in payload:
                                user_id = int(payload['Id'])
                                logger.debug(f"从token中提取用户ID: {user_id}")
                    except Exception as e:
                        logger.error(f"提取用户ID失败: {e}")
                
                # 记录从 user_info 获取的 UK 值
                uk_value = user_info.get('uk', '')
                logger.debug(f"从 user_info 获取的 UK 值: {uk_value}")
                logger.debug(f"user_info 完整内容: {user_info}")
                
                # 保存账号数据
                self.account_data = {
                    'user_id': user_id,
                    'uu_user_id': user_id,  # 添加uu_user_id字段，与user_id保持一致
                    'nickname': user_info.get('nickname', ''),
                    'token': user_info.get('token', ''),
                    'device_id': user_info.get('device_id', ''),
                    'uk': uk_value
                }
                logger.debug(f"登录成功，保存的账号数据: {self.account_data}")
                logger.debug(f"保存到 account_data 的 UK 值: {self.account_data.get('uk', '无UK值')}")
                self.accept()
            else:
                # 登录失败
                logger.error("登录失败，返回为空")
                QMessageBox.warning(self, "错误", "登录失败，请检查验证码是否正确或重新发送验证码")
        except Exception as e:
            logger.error(f"登录异常: {str(e)}")
            QMessageBox.warning(self, "错误", f"登录出错: {str(e)}")
